<?php

namespace backend\models;

use common\helps\tools;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Query;
use common\helps\tree;
/**
 * This is the model class for table "auth_group".
 *
 */
class AuthGroup extends ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
      return '{{%auth_group}}';
    }



    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title','rules'], 'trim'],
            [['id','title','role_level'], 'required', 'message'=>'{attribute}不能为空'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '角色id',
            'title' => '角色名称',
            'rules'=>'权限字符串',
        ];
    }


    public function scenarios()
    {
        return [
            'default' => [
                'module',
                'role_level',
                'title',
                'status',
                'rules',
                'notation',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
            'create' => [
                'module',
                'role_level',
                'title',
                'status',
                'rules',
                'notation',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
            'update' => [
                'id',
                'module',
                'role_level',
                'title',
                'status',
                'rules',
                'notation',
                'created_at',
                'updated_at',
                'deleted_at'
            ],
        ];
    }

    /**
     * @param $params
     * @param $user_id
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getAuthList($params){
        $condition['status']=1;
        $auth_access = new AuthGroupAccess();
        $admin_model = new Admin();
        $list = (new Query())
            ->select('id,title,role_level,notation')
            ->from('auth_group')
            ->where($condition)
            ->all();
        if($params['type']>1){  // 编辑授权角色
            $user_id=intval($params['id']);
            $group_role_ids = $auth_access->find()->select('group_role_id')->where(['and','uid='.intval($user_id),['deleted_at'=>null]])->asArray()->all();
            $user_info = $admin_model->find()->where(['id'=>intval($user_id)])->asArray()->one();
            $data['user_info'] = $user_info;
            if(!empty($group_role_ids)){
                $group_role_ids=array_column($group_role_ids, 'group_role_id');
            }
            if(count($list)){
                foreach($list as &$value){
                    if(in_array($value['id'],$group_role_ids)){
                        $value['is_check'] =1;
                    }
                }
            }
        }

//        if($params['type']==1){
//            $condition = ['and','status=1',['in','id',array_column($group_role_ids, 'group_role_id')],['deleted_at'=>null]];
//        }else{
//            $condition = ['and','status=1',['not in','id',array_column($group_role_ids, 'group_role_id')],['deleted_at'=>null]];
//        }
//        $list = $this->find()->select('id,title,role_level,notation')->where($condition)->asArray()->all();
        $data['role_list'] = empty($list)?array():$list;
        return $data;
    }


    /**
     * 获取角色列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getAuthGroupList($params){
        if(!empty($params['title'])){
            $condition = ['and','status=1',['like','title',$params['title']],['deleted_at'=>null]];
        }else{
            $condition['status']=1;
        }
        $list = (new Query())
            ->select('id,title,notation')
            ->from('auth_group')
            ->where($condition)
            ->all();
        return empty($list)?array():$list;

    }


    /**
     * 删除角色
     * @param $role_id
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function deleteRole($role_id){
        $model = static::findOne(['id' =>$role_id]);
        if(empty($model)) return false;
        $params['status'] = 3;
        $params['deleted_at'] = time();
        $model->scenario = 'update';
        $model->setAttributes($params, false);
        if (!$model->save()) {
            return false;
        }else{
            return true;
        }
    }

    /**
     * 获取会员menu 权限
     * @param $role_id
     * @author hey_heyang(635870453@qq.com)
     */
    public  function  getRoleAuthList($role_id){
        $redis = Yii::$app->cache;
        $role_auth = json_decode($redis->hget('role_auth' ,'role_'.$role_id),true);
        if(empty($role_auth)){
            $auth_array = (new Query())
                ->select('*')
                ->from('auth_rule')
                ->where(['and','status=1', 'module="admin"',['deleted_at'=>null]])
                ->orderBy('sorts ASC,id DESC')
                ->all();
            //获取全部树型结构
            if(!empty($auth_array)){
                $tree = new tree();
                $auth_array = $tree->create($auth_array);
            }
            $redis->hdel('role_auth','role_0');
            $redis->hset('role_auth','role_0',json_encode($auth_array));

            if($role_id>=0){
                $rules = (new Query())
                    ->select('rules')
                    ->from('auth_group')
                    ->where(['and','status=1','id='.$role_id])
                    ->one();

                $rulesArr = explode(',', $rules['rules']);   //以前就拥有的权限节点
                foreach ($auth_array as &$val){
                    if(in_array($val['id'], $rulesArr)){
                        $val['ischeck'] = 1;
                    }else {
                        continue;
                    }
                    if(!empty($val['child'])){  //二级操作
                        foreach($val['child'] as &$v1){
                            if(in_array($v1['id'], $rulesArr)){
                                $v1['ischeck'] = 1;
                            }else {
                                continue;
                            }
                            if(!empty($v1['child'])){  //三级操作
                                foreach($v1['child'] as &$v2){
                                    if(in_array($v2['id'], $rulesArr)){
                                        $v2['ischeck'] = 1;
                                    }else {
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
                $redis->hdel('role_auth','role_'.$role_id);
                $redis->hset('role_auth','role_'.$role_id,json_encode($auth_array));
            }
        }else{
            $auth_array = $role_auth;
        }



            return empty($auth_array)?array():array_values($auth_array);

    }

    /**
     * 新增与编辑角色
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editRole($param){
        if($param['type']>1){ //编辑
            $model = static::findOne(['id' =>$param['id']]);
            if(empty($model)) return array('error'=>'未查询到角色信息');
            $model->scenario = 'update';
        }else{
            $model = new self();
            $model->scenario = 'create';
            unset($param['id']);
        }
        $model->setAttributes($param, false);
        if (!$model->save()) {
            return array('error'=>'操作失败');
        }else{
            tools::delAuthCache();
            return array('error'=>'');
        }
    }



}
